import axios from 'axios'
import {Message} from 'element-ui';
import router from '../router'
import {mymessage} from '@/utils/mymessage';

axios.interceptors.response.use(success => {    //对axios进行了简单的封装，这里主要使用了axios中的拦截器功能。在接收到response时提示message，从而避免在每次请求时都去判断各种各样的网络情况
    // console.log(success)
    if (success.status && success.status == 200 && success.data.status == 500) {
        Message.error({message: success.data.msg})
        return;
    }
    if (success.data.msg) {
        Message.success({message: success.data.msg})
    }
    return success.data;
}, error => {
    if (error.response.status == 504 || error.response.status == 404) {
        Message.error({message: '服务器被吃了( ╯□╰ )'})
    } else if (error.response.status == 403) {
        Message.error({message: '权限不足，请联系管理员'})
    } else if (error.response.status == 401) {
        mymessage.error({message: error.response.data.msg ? error.response.data.msg : '尚未登录，请登录'})
        router.replace('/');
    } else {
        if (error.response.data.msg) {
            Message.error({message: error.response.data.msg})
        } else {
            Message.error({message: '未知错误!'})
        }
    }
    return;
})

// let base = 'http://192.168.0.111:8081';
// let base = 'http://124.220.15.11:8081';
let base = "";  //如果未指定baseUrl，那就走浏览器地址栏里的base + baseUrl 即localhost8080
// tips：在开发环境中：axios中不用配置baseUrl，会自动匹配vue.config,js中的target，所以在生产环境中需要配置baseUrl，以防止打包后请求不到接口路径
// let base = "http://localhost:80/nginx";

export const postKeyValueRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            }
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
}
export const postRequest = (url, params) => {  // 函数的返回值是个函数，相当于把axios的不同请求封装成了多个全局函数
    // console.log(`${base}${url}`)
    return axios({
        method: 'post',
        url: `${base}${url}`,          // 在开发环境中：axios中不用配置baseUrl，会自动匹配vue.config,js中的target；在生产环境中需要配置baseUrl，以防止打包后请求不到接口路径
        data: params                   // postrequest用于发送数据包
    })
}
export const putRequest = (url, params) => {
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params
    })
}
export const getRequest = (url, params) => {
    return axios({
        method: 'get',
        url: `${base}${url}`,
        params: params
    })
}
export const deleteRequest = (url, params) => {
    return axios({
        method: 'delete',
        url: `${base}${url}`,
        params: params
    })
}
